<template>
  <div class="test-auth-page">
    <h2>认证API测试</h2>
    
    <el-card class="test-card">
      <template #header>
        <span>登录测试</span>
      </template>
      
      <el-form :model="loginForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="testLogin" :loading="loginLoading">测试登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <span>注册测试</span>
      </template>
      
      <el-form :model="registerForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="registerForm.real_name" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="身份证">
          <el-input v-model="registerForm.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="registerForm.user_type" placeholder="请选择用户类型">
            <el-option label="普通用户" value="user" />
            <el-option label="律师" value="lawyer" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="testRegister" :loading="registerLoading">测试注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <span>简化注册测试</span>
      </template>
      
      <el-button type="success" @click="testSimpleRegister" :loading="simpleRegisterLoading">
        测试简化注册（硬编码数据）
      </el-button>
      
      <div class="json-display" v-if="simpleRegisterResult">
        <h4>简化注册结果：</h4>
        <pre>{{ simpleRegisterResult }}</pre>
      </div>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <span>API连接测试</span>
      </template>
      
      <el-button type="info" @click="testApiConnection" :loading="apiTestLoading">
        测试API连接
      </el-button>
      
      <div class="json-display" v-if="apiTestResult">
        <h4>API连接测试结果：</h4>
        <pre>{{ apiTestResult }}</pre>
      </div>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <span>请求数据</span>
      </template>
      
      <div class="json-display">
        <h4>登录请求数据：</h4>
        <pre>{{ loginRequestData }}</pre>
      </div>
      
      <div class="json-display">
        <h4>注册请求数据：</h4>
        <pre>{{ registerRequestData }}</pre>
      </div>
      
      <div class="json-display">
        <h4>请求URL：</h4>
        <pre>{{ requestUrls }}</pre>
      </div>
    </el-card>
    
    <el-card class="test-card">
      <template #header>
        <span>响应结果</span>
      </template>
      
      <div class="json-display">
        <h4>登录响应：</h4>
        <pre>{{ loginResponse }}</pre>
      </div>
      
      <div class="json-display">
        <h4>注册响应：</h4>
        <pre>{{ registerResponse }}</pre>
      </div>
      
      <div class="json-display">
        <h4>错误信息：</h4>
        <pre>{{ errorMessage }}</pre>
      </div>
    </el-card>

    <el-card class="test-card">
      <template #header>
        <span>字段映射测试</span>
      </template>
      
      <el-form :model="fieldTestForm" label-width="100px">
        <el-form-item label="用户类型字段名">
          <el-select v-model="fieldTestForm.fieldName" placeholder="选择字段名">
            <el-option label="userType" value="userType" />
            <el-option label="realName" value="realName" />
            <el-option label="roleIds" value="roleIds" />
            <el-option label="username" value="username" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户类型值">
          <el-select v-model="fieldTestForm.fieldValue" placeholder="选择值">
            <el-option label="PUBLIC" value="PUBLIC" />
            <el-option label="LAWYER" value="LAWYER" />
            <el-option label="ADMIN" value="ADMIN" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="testFieldMapping" :loading="fieldTestLoading">
            测试字段映射
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="json-display" v-if="fieldTestResult">
        <h4>字段映射测试结果：</h4>
        <pre>{{ fieldTestResult }}</pre>
      </div>
    </el-card>
    
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/api/index'

const loginForm = ref({
  username: 'example_user1',
  password: 'Pssw0rd123'
})

const registerForm = ref({
  username: 'test_user_' + Date.now(),
  email: 'test@example.com',
  phone: '13800138000',
  real_name: '测试用户',
  idCard: '110101199001011234',
  password: 'Test123456',
  user_type: 'user'
})

const fieldTestForm = ref({
  fieldName: 'userType',
  fieldValue: 'PUBLIC'
})

const loginRequestData = ref('')
const registerRequestData = ref('')
const requestUrls = ref('')
const loginResponse = ref('')
const registerResponse = ref('')
const errorMessage = ref('')
const loginLoading = ref(false)
const registerLoading = ref(false)
const apiTestLoading = ref(false)
const apiTestResult = ref('')
const fieldTestLoading = ref(false)
const fieldTestResult = ref('')
const simpleRegisterLoading = ref(false)
const simpleRegisterResult = ref('')

const testLogin = async () => {
  try {
    loginLoading.value = true
    loginResponse.value = ''
    errorMessage.value = ''
    
    // 显示请求数据
    loginRequestData.value = JSON.stringify(loginForm.value, null, 2)
    requestUrls.value = 'POST /api/user/login'
    
    // 发送登录请求
    const response = await userAPI.login(loginForm.value)
    
    // 显示响应数据
    loginResponse.value = JSON.stringify(response, null, 2)
    ElMessage.success('登录请求发送成功')
    
  } catch (error) {
    // 显示错误信息
    errorMessage.value = JSON.stringify({
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data
    }, null, 2)
    
    ElMessage.error('登录请求失败：' + error.message)
  } finally {
    loginLoading.value = false
  }
}

const testRegister = async () => {
  try {
    registerLoading.value = true
    registerResponse.value = ''
    errorMessage.value = ''
    
    // 构建注册数据
    const userData = {
      username: registerForm.value.username,
      email: registerForm.value.email,
      phone: registerForm.value.phone,
      realName: registerForm.value.real_name, // 后端期望的字段名
      idCard: registerForm.value.idCard,
      password: registerForm.value.password,
      userType: registerForm.value.user_type === 'user' ? 'PUBLIC' : 
               registerForm.value.user_type === 'lawyer' ? 'LAWYER' : 'ADMIN', // 后端期望的值格式
      avatar: registerForm.value.avatar || '',
      status: 1,
      roleIds: [1] // 默认角色ID
    }
    
    // 显示请求数据
    registerRequestData.value = JSON.stringify(userData, null, 2)
    requestUrls.value = 'POST /api/user/create'
    
    // 调试：打印实际发送的数据
    console.log('🔍 发送的注册数据:', userData)
    console.log('🔍 userType 值:', userData.userType)
    console.log('🔍 realName 值:', userData.realName)
    console.log('🔍 roleIds 值:', userData.roleIds)
    
    // 发送注册请求
    const response = await userAPI.create(userData)
    
    // 显示响应数据
    registerResponse.value = JSON.stringify(response, null, 2)
    ElMessage.success('注册请求发送成功')
    
    // 更新登录表单
    loginForm.value.username = registerForm.value.username
    loginForm.value.password = registerForm.value.password
    
  } catch (error) {
    // 显示错误信息
    errorMessage.value = JSON.stringify({
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data
    }, null, 2)
    
    ElMessage.error('注册请求失败：' + error.message)
  } finally {
    registerLoading.value = false
  }
}

const testSimpleRegister = async () => {
  try {
    simpleRegisterLoading.value = true
    simpleRegisterResult.value = ''

    const userData = {
      username: 'simple_user_' + Date.now(),
      email: 'simple@example.com',
      phone: '13800138001',
      realName: '简单用户',
      idCard: '110101199001011235',
      password: 'Simple123',
      userType: 'PUBLIC',
      avatar: '',
      status: 1,
      roleIds: [1]
    };

    const response = await userAPI.create(userData);
    simpleRegisterResult.value = JSON.stringify({
      message: '简化注册成功',
      data: response
    }, null, 2);
    ElMessage.success('简化注册请求发送成功');

  } catch (error) {
    simpleRegisterResult.value = JSON.stringify({
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data
    }, null, 2);
    ElMessage.error('简化注册请求失败：' + error.message);
  } finally {
    simpleRegisterLoading.value = false;
  }
};

const testApiConnection = async () => {
  try {
    apiTestLoading.value = true
    apiTestResult.value = ''
    
    // 尝试发送一个简单的请求来测试API连接
    const response = await userAPI.getList() // 使用获取用户列表的API端点
    
    apiTestResult.value = JSON.stringify({
      message: 'API连接正常',
      data: response
    }, null, 2)
    ElMessage.success('API连接测试成功！')
  } catch (error) {
    apiTestResult.value = JSON.stringify({
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data
    }, null, 2)
    ElMessage.error('API连接测试失败：' + error.message)
  } finally {
    apiTestLoading.value = false
  }
}

const testFieldMapping = async () => {
  try {
    fieldTestLoading.value = true
    fieldTestResult.value = ''

    const fieldName = fieldTestForm.value.fieldName
    const fieldValue = fieldTestForm.value.fieldValue

    // 测试不同的字段名映射
    const testData = {
      username: 'test_user_' + Date.now(),
      email: 'test@example.com',
      phone: '13800138000',
      password: 'Test123',
      idCard: '110101199001011234',
      avatar: '',
      status: 1,
      roleIds: [1]
    }

    // 根据选择的字段名添加字段
    if (fieldName === 'userType') {
      testData.userType = fieldValue
    } else if (fieldName === 'realName') {
      testData.realName = fieldValue
    } else if (fieldName === 'roleIds') {
      testData.roleIds = [parseInt(fieldValue)]
    } else if (fieldName === 'username') {
      testData.username = fieldValue
    }

    console.log('🔍 测试数据:', testData)

    // 尝试发送注册请求
    const response = await userAPI.create(testData)

    fieldTestResult.value = JSON.stringify({
      message: '字段映射测试成功',
      fieldName: fieldName,
      fieldValue: fieldValue,
      testData: testData,
      response: response
    }, null, 2)
    ElMessage.success('字段映射测试成功！')
  } catch (error) {
    fieldTestResult.value = JSON.stringify({
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data
    }, null, 2)
    ElMessage.error('字段映射测试失败：' + error.message)
  } finally {
    fieldTestLoading.value = false
  }
}
</script>

<style scoped>
.test-auth-page {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.test-card {
  margin-bottom: 20px;
}

.json-display {
  margin-bottom: 20px;
}

.json-display h4 {
  margin-bottom: 10px;
  color: #333;
}

.json-display pre {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  border: 1px solid #ddd;
  overflow-x: auto;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
}
</style> 